<template>
    <div v-if="cartList.length > 0">
        <el-row class="title">
            <el-col :span="2">
                <el-checkbox
                    label="全选"
                    :true-label="1" :false-label="0"
                    v-model="checkAllState"
                    :indeterminate="halfState"
                    @change="checkAllOrNone" />
            </el-col>
            <el-col :span="8">商品</el-col>
            <el-col :span="2">单价</el-col>
            <el-col :span="6">数量</el-col>
            <el-col :span="2">小计</el-col>
            <el-col :span="1">操作</el-col>
        </el-row>
        <el-row v-for="(cart, index) in cartList" :key="index" class="cartItem">
            <el-col :span="2">
                <el-checkbox :true-label="1" :false-label="0" v-model="cart.selected" @change="changeState(cart)" />
            </el-col>
            <el-col :span="2">
                <el-image
                    :src="cart.productImage"
                    style="height: 50px; width: 50px;"
                    fit="contain"/>
            </el-col>
            <el-col :span="6">{{ cart.productName }}</el-col>
            <el-col :span="2">{{ cart.productPrice }}</el-col>
            <el-col :span="6">
                <el-input-number
                    v-model="cart.count"
                    :min="1"
                    size="small"
                    @change="updateCount(cart)" />
            </el-col>
            <el-col :span="2">{{ (cart.productPrice * cart.count).toFixed(2) }}</el-col>
            <el-col :span="1">
                <el-button type="danger" :icon="Delete" circle @click="deleteById(cart.id)" />
            </el-col>
        </el-row>
        <el-row class="cartFooter">
            <el-col :span="2">
                <el-checkbox
                    label="全选"
                    :true-label="1" :false-label="0"
                    v-model="checkAllState"
                    :indeterminate="halfState"
                    @change="checkAllOrNone" />
            </el-col>
            <el-col :span="3">
                <el-link :underline="false" @click="deleteChecked">删除选中的商品</el-link>
            </el-col>
            <el-col :span="11">
                <el-link :underline="false" @click="deleteAll">清理购物车</el-link>
            </el-col>
            <el-col :span="3">
                已选择{{checkedCount}}件商品
            </el-col>
            <el-col :span="3">
                总价: ￥{{ total.toFixed(2) }}
            </el-col>
            <el-col :span="2">
                <el-button type="danger" @click="toCreateOrderPage">结算</el-button>
            </el-col>
        </el-row>
    </div>
    <div v-else class="none">
        购物车空空的哦~，去看看心仪的商品吧~<RouterLink to="/index">去购物</RouterLink>
    </div>
</template>

<script setup>
import {ref} from "vue";
import cartApi from "@/api/cartApi.js";
import {Delete} from "@element-plus/icons-vue";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";

const router = useRouter();
//服务器地址
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
//当前用户所有的购物车信息
const cartList = ref([]);
//全选按钮是否选中
const checkAllState = ref(0);
//没有全选的状态
const halfState = ref(false);
//选中商品的数量
const checkedCount = ref(0);
//选中商品的总金额
const total = ref(0);

//跳转到生成订单页面
function toCreateOrderPage() {
    //获取已选中的购物车ID
    let cartIds = [];

    cartList.value.forEach(cart => {
        if(cart.selected) {
            cartIds.push(cart.id);
        }
    });

    if(cartIds.length == 0) {
        ElMessage.warning("您还没有选择商品，无法进行结算");
        return;
    }

    router.push({
        path: "/createOrder",
        query: {
            cartIds
        }
    });
}

//删除已选择的购物车
function deleteChecked() {
    let ids = [];
    cartList.value.forEach(cart => {
        if(cart.selected) {
            ids.push(cart.id);
        }
    });

    if(ids.length == 0) {
        ElMessage.warning("没有选择购物车，无法删除~~~");
        return;
    }

    //批量删除
    cartApi.deleteByIds(ids)
        .then(resp => {
            if(resp.code == 10000) {
                ElMessage.success(resp.msg);
                //保留没有被选中的购物车
                cartList.value = cartList.value.filter(cart => !cart.checkState);
                //重新设置全选按钮的状态 - 重新计算总金额和数量
                changeState();
            } else {
                ElMessage.error(resp.msg);
            }
        })
}

//清空购物车
function deleteAll() {
    let ids = [];
    cartList.value.forEach(cart => {
        ids.push(cart.id);
    });

    if(ids.length == 0) {
        ElMessage.warning("购物车中没有商品，无法删除~~~");
        return;
    }

    //批量删除
    cartApi.deleteByIds(ids)
        .then(resp => {
            if(resp.code == 10000) {
                ElMessage.success(resp.msg);
                //重新获取购物车列表
                selectCartList();
                //重新设置全选按钮的状态 - 重新计算总金额和数量
                changeState();
            } else {
                ElMessage.error(resp.msg);
            }
        })
}

//全选 - 全不选
function checkAllOrNone() {
    //让每个购物车项前面的多选按钮的状态和全选按钮的状态保持一致
    cartList.value.forEach(cart => {
        debugger
        cart.selected = checkAllState.value;
        cartApi.update(cart).then(result => {
            getCountAndTotal();
        })
    });
}

//购物车项前面的多选按钮状态发生变化时调用的函数
function changeState(cart) {
    console.log('当前选中商品：', cart)
    cartApi.update(cart).then(result => {
        ElMessage.success(result.msg);
        /*
        * 设置全选按钮的状态
        *   1. 如果所有的checkbox都被选中，设置全选按钮选中
        *   2. 如果所有的checkbox都没被选中，设置全选按钮没有选中
        * 重新计算选中的商品数量
        * 重新计算选中商品的金额
        * */
        let count = 0; //表示被选中的checkbox的数量
        cartList.value.forEach(cart => {
            if (cart.selected) {
                count++; //计算被选中的checkbox的数量
            }
        });

        if(count == cartList.value.length) {
            checkAllState.value = 1;
            halfState.value = false;
        } else if(count == 0) {
            checkAllState.value = 0;
            halfState.value = false;
        } else {
            halfState.value = true;
        }
        getCountAndTotal();
    })
}

//计算选中商品的数量和金额
function getCountAndTotal() {
    checkedCount.value = 0;
    total.value = 0;
    cartList.value.forEach(cart => {
        if (cart.selected) {
            checkedCount.value += cart.count; //计算选中的商品数量
            total.value += cart.productPrice * cart.count; //计算选中商品的金额
        }
    });
}

//查询当前用户所有的购物车信息
function selectCartList() {
    cartApi.list().then(resp => {
        cartList.value = resp.data;
        //更新状态
        changeState()
    });
}

//根据id删除
function deleteById(id) {
    cartApi.deleteById(id).then(resp => {
        ElMessage.success(resp.msg);
        //将被删除的项从cartList中清除
        cartList.value = cartList.value.filter(cart => cart.id != id);
        //设置全选按钮的状态
        changeState();
        getCountAndTotal();
    })
}

//修改购物车商品数量
function updateCount(cart) {
    const cartInfo = {
        id: cart.id,
        count: cart.count
    };
    cartApi.update(cartInfo).then(result => {
        ElMessage.success(result.msg);
        //让购物车中商品数量和数据库中保持一致
        // cartApi.selectById(cartInfo.id).then(result => {
        //     cartList.value.forEach(cart => {
        //         if(cart.id == cartInfo.id) {
        //             cart.count = result.data.count;
        //         }
        //     });
        // });
        getCountAndTotal();
    })
}

selectCartList();
</script>

<style scoped>
    .title, .cartFooter {
        margin: 20px 0;
        padding-left: 10px;
        font-size: 14px;
        background-color: #FFF;
        height: 40px;
        line-height: 40px;
    }

    .cartItem {
        margin-bottom: 5px;
        padding-left: 10px;
        font-size: 14px;
        background-color: #FFF;
        height: 50px;
        line-height: 50px;
    }

    .none {
        line-height: 300px;
        height: 300px;
        background-color: #FFF;
        text-align: center;
    }
</style>